﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Research.Kinect.Nui;
using System.Reactive.Subjects;

namespace Kinect.KinectMouseControl
{
    public class KinectFramesPerSecondObserver : IEventPublisher<int>
    {
        private IEventPublisher<SkeletonFrame> _skeletonFramePublisher;
        private Subject<int> _framePerSecondSubject;
        private DateTime _lastFrame;

        public KinectFramesPerSecondObserver(IEventPublisher<SkeletonFrame> skeletonFramePublisher)
        {
            _skeletonFramePublisher = skeletonFramePublisher;
            _skeletonFramePublisher.EventObservable.Subscribe(x => CalculateFramePerSecond(x));
            _framePerSecondSubject = new Subject<int>();
        }

        private void CalculateFramePerSecond(SkeletonFrame x)
        {
            var difference = DateTime.Now.Subtract(_lastFrame);
            if (difference.TotalMilliseconds > 0)
            {
                _framePerSecondSubject.OnNext(Convert.ToInt32(1000 / difference.TotalMilliseconds));
            }
            _lastFrame = DateTime.Now;
        }

        #region IEventPublisher<int> Members

        public IObservable<int> EventObservable
        {
            get { return _framePerSecondSubject; }
        }

        #endregion
    }
}
